package com.example.badminton.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.badminton.common.AnonymousAccess;
import com.example.badminton.common.Result;
import com.example.badminton.entity.Court;
import com.example.badminton.service.CourtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/court")
@CrossOrigin
public class CourtController {
    
    @Autowired
    private CourtService courtService;

    /**
     * 获取场地列表
     */
    @AnonymousAccess
    @GetMapping("/list")
    public Result<List<Court>> list(
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String keyword) {
        try {
            QueryWrapper<Court> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1); // 只查询可用的场地
            
            if (type != null && !type.isEmpty()) {
                queryWrapper.eq("type", type);
            }
            
            if (keyword != null && !keyword.isEmpty()) {
                queryWrapper.and(wrapper -> wrapper
                    .like("name", keyword)
                    .or()
                    .like("description", keyword)
                );
            }
            
            queryWrapper.orderByAsc("sort").orderByDesc("create_time");
            List<Court> courts = courtService.list(queryWrapper);
            return Result.success(courts);
        } catch (Exception e) {
            return Result.error("获取场地列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取场地详情
     */
    @AnonymousAccess
    @GetMapping("/{id}")
    public Result<Court> detail(@PathVariable Long id) {
        try {
            Court court = courtService.getById(id);
            if (court != null) {
                return Result.success(court);
            } else {
                return Result.error("场地不存在");
            }
        } catch (Exception e) {
            return Result.error("获取场地详情失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取热门场地（前3个）
     */
    @AnonymousAccess
    @GetMapping("/hot")
    public Result<List<Court>> getHotCourts() {
        try {
            QueryWrapper<Court> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1);
            queryWrapper.orderByAsc("sort").orderByDesc("create_time");
            queryWrapper.last("LIMIT 3");
            List<Court> courts = courtService.list(queryWrapper);
            return Result.success(courts);
        } catch (Exception e) {
            return Result.error("获取热门场地失败: " + e.getMessage());
        }
    }
} 